// pages/reserve/personal/index.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        logid:0,
        topNavH:'',
        invalidTime:[],//禁止预约时间段
        timeIndex:-1,//所选时间
        dateIndex:0,//所选日期
        scene:null,
        showDateModal:false,//选择预约弹窗标志
        user:{//访问用户信息模板
          name:'',
          company:'',
          mobile:'',
          idcard:'',
          leader:'',
          duty:'',
        },
        seconds:5,
        noticeTips:false,
        notice:null,
        visitNum:10,//访问人数
        reservetime:'',//预约时间
        // checkInvalids:{'09:00':true,},
        checkInvalids:null,//禁止预约时间段
        reserveMax:50,//最大预约人数
        reserveInfo:null, //所有预约人数时间段信息
        dateReserveInfo:null,//当日已预约人数信息
        reserveSuccess:false,//预约结果
        msg:'',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that = this;
        const res = wx.getSystemInfoSync() 
        let menu = wx.getMenuButtonBoundingClientRect();
        
        console.log('get System info', res)
        var statusBarHeight = res.statusBarHeight;
        let navBarHeight = (menu.top-statusBarHeight)*2+menu.height; 
        console.log('statusBarHeight:' + navBarHeight)
        var topNavH = (statusBarHeight + navBarHeight);
        that.setData({
            topNavH: topNavH + 'px',
        }) 
        if(options.logid){
          this.data.logid = options.logid;
        }
        this.getReserveInfo();
        this.getInvalidTime();
    },

    getReserveInfo(){
        const that = this;
        wx.request({
          url: app.globalData.apiUrl + 'api/reserve/index',
          method: 'POST',
          data: {
            'openid':wx.getStorageSync('openid'),
            'type':2
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            let response = res.data.data;
            that.setData({
                scene:response.scene,
                reserveInfo:response.reserveInfo,
                reserveMax:response.maxnum,
                notice:response.notice,
                seconds:response.notice.count,
                noticeTips:response.notice.noticeTips
            }) 

            if(that.data.seconds>0) {
              let interval = setInterval(()=>{

                  if(that.data.seconds>0) {
                    that.data.seconds = that.data.seconds-1;
                    that.setData({
                      seconds:that.data.seconds
                    })
                  }
                  else {
                    clearInterval(interval);
                  }
              }, 1000);
            }
            if(that.data.logid == 0) {
              const keys = Object.keys(response.scene.dateArr); 
               that.setData({
                dateIndex:keys[0]
               })
              
            }
            that.setReserveInfo();
            that.getReserveLog();
          },
          fail: function () {
            
          },
          complete: function () {
          }
        })
      },
    getReserveLog(){
      const that = this;
      if(this.data.logid>0) {
        wx.request({
          url: app.globalData.apiUrl + 'api/reserve/detail',
          method: 'POST',
          data: {
            'openid':wx.getStorageSync('openid'),
            'logid':that.data.logid
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            let response = res.data.data;
            that.setData({
              dateIndex:response.dateIndex,
              user:response.user,
              reservetime:response.date+' '+response.time
             }) 
             that.setInvalidTime();
             that.setReserveInfo();
          },
        })
      }
    },
    getInvalidTime(){
        const that = this;
        wx.request({
          url: app.globalData.apiUrl + 'api/reserve/invalidTime',
          method: 'POST',
          data: {
            'type':2,
            'sceneid':1,
            'logid':this.data.logid
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            let response = res.data;
            if(res.data){
               that.setData({
                invalidTime:response.data
               })
               that.setInvalidTime();
            }
            
            
          },
          fail: function () {
            
          },
          complete: function () {
          }
        })
      },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    switchDate(e){
        let index = e.currentTarget.dataset.index;
        console.log(index, e)
        this.setData({
          dateIndex:index,
          timeIndex:-1,
        })
        this.setInvalidTime();
        this.setReserveInfo();
    },
    calDate(time=''){
      if(this.data.dateIndex>0){
        let str = this.data.scene.dateArr[this.data.dateIndex].time +' '+time;
        return Date.parse(str)/1000;
      }
      return 0;
    },//计算预约剩余数量
    setReserveInfo(){
      const that = this;
      let tmp = {};
      for (let index = 0; index < that.data.scene.timeArr.length; index++) {
        let timestamp = this.calDate(that.data.scene.timeArr[index]);
        if(timestamp>0 &&  this.data.reserveInfo[timestamp]) {
          tmp[index] = this.data.reserveMax - this.data.reserveInfo[timestamp];
        }
        else {
          tmp[index] = this.data.reserveMax;
        }
      }
      this.setData({
        dateReserveInfo:tmp
      })
    },
    setInvalidTime(){
      if(this.data.invalidTime[this.data.dateIndex] && 
        this.data.invalidTime[this.data.dateIndex].length>0){
        let tmp = {};
        for (let index = 0; index < this.data.invalidTime[this.data.dateIndex].length; index++) {
          const element = this.data.invalidTime[this.data.dateIndex][index];
          tmp[element] = true;
        }
        this.setData({
          checkInvalids:tmp
        })
      }
      else{
        this.setData({
          checkInvalids:null
        })
      }
    },
    selectTime(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index, e)
        let time = this.data.scene.timeArr[index];
        if(this.data.checkInvalids && this.data.checkInvalids[time]) {
          wx.showToast({
            icon:'none',
            title: '时间段已被预约',
          })
          return ;
        }
        //checkInvalids
        this.setData({
            timeIndex:index
        })
    },//预约弹窗
    closeDateModal(){
      this.setData({
          showDateModal:false
      });
    },
    openDateModal(){
      this.setData({
        showDateModal:true
    });
    },
    stopEmitter(){},
    delExtendUser(){//减少参观人数
      if(this.data.visitNum<=10) return;
      this.setData({
        visitNum:(this.data.visitNum-1)
      })
    },
    addExtendUser(){
      if(this.data.visitNum>= this.data.reserveMax) return;
      this.setData({
        visitNum:(this.data.visitNum+1)
      })
    },
    setUser(e){
      let key = e.currentTarget.dataset.key;
      this.data.user[key] = e.detail.value;
    },//入馆时间设置  提交表单校验
    confirmDate(){
      if(this.data.dateIndex && this.data.timeIndex>=0) {
        let str = this.data.scene.dateArr[this.data.dateIndex].time +' '+this.data.scene.timeArr[this.data.timeIndex];
        this.setData({
          reservetime:str
        })
      }
      this.setData({
        showDateModal:false
      })
    },
    doSubmit(){
        const that = this;
        if(!this.data.reservetime) {
          wx.showToast({icon:'error',title: '请选择入馆时间',})
          return;
        }
        if(!this.data.user.name) {
          wx.showToast({icon:'error',title: '请填写您的姓名',})
          return;
        }
        if(!this.data.user.mobile) {
          wx.showToast({icon:'error',title: '请填写您的手机号',})
          return;
        }
        if(!this.data.user.idcard) {
          wx.showToast({icon:'error',title: '请填写您的身份证号',})
          return;
        }
        if(!this.data.user.company) {
          wx.showToast({icon:'error',title: '请填写公司名称',})
          return;
        }
        
        if(this.data.logid>0) {
          this.updateReserve();
          return ;
        }

        let data = {
          reservetime:this.data.reservetime,
          num:this.data.visitNum,
          sceneid:this.data.scene.id,
          openid:wx.getStorageSync('openid'),
          type:2,
          user:this.data.user,
          extend_user:[]
        };

        wx.request({
          url: app.globalData.apiUrl + 'api/reserve/appoint',
          method: 'POST',
          data: data,
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            let response = res.data;
            if(response.code==1){
              that.setData({
                msg:response.msg,
                reserveSuccess:true,
              })
            }
            else {
              // wx.showToast({icon:'none',title: response.msg,})
              wx.showModal({
                title: '预约失败通知',
                content: response.msg
              })
            }
          },
          fail: function () {
            
          },
          complete: function () {
          }
        })
    },
    updateReserve(){
      const that = this;
      let data = {
        logid:this.data.logid,
        reservetime:this.data.reservetime,
        num:this.data.visitNum,
        sceneid:this.data.scene.id,
        openid:wx.getStorageSync('openid'),
        type:2,
        user:this.data.user,
        extend_user:[]
      };

      wx.request({
        url: app.globalData.apiUrl + 'api/reserve/update',
        method: 'POST',
        data: data,
        header: {
          'Content-Type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          let response = res.data;
          console.log(response);
          if(response.code==1){
            // wx.showToast({icon:'none',title: response.msg})
            that.setData({
              msg:response.msg,
              reserveSuccess:true,
            })
          }
          else {
            // wx.showToast({icon:'none',title: response.msg,})
            wx.showModal({
              title: '预约失败通知',
              content: response.msg
            })
          }
        },
        fail: function () {
          
        },
        complete: function () {
        }
      })
    },
    closeReserveResult(){
      this.setData({
        reserveSuccess:false,
      })
      setTimeout(()=>{
        wx.switchTab({
          url: '/pages/reserve/index/index',
        })
      }, 100);
    },
    closeTips(){
      if(this.data.seconds>0) return ;
      this.setData({
        noticeTips:false,
      })
    },
    previewDocs(e) {
      let index = e.currentTarget.dataset.index;
      let item = this.data.notice.files[index];
      console.log(index)
      console.log(item)
      // return ;
      wx.downloadFile({
        // 示例 url，并非真实存在
        url: item.path,
        filePath:wx.env.USER_DATA_PATH+'/'+item.name,
        success: function (res) {
          console.log(res)
          const filePath = res.filePath
          wx.openDocument({
            filePath: filePath,
            showMenu:true,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        }
      })
    }
})